package com.hundsun.yr.universal.library.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

import com.hundsun.yr.universal.library.R;

/**
 * @Title: ClickableTextView.java
 * @Description: 带有按下效果的TextView
 * @date 2015-10-15 下午4:12:18
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 * @version V1.0
 */
public class ClickableTextView extends TextView {

	private int mTextColor_n = -1;// 普通填充色
	private int mTextColor_p = -1;// 按下填充色
	private static final int DEFAULT_TEXT_COLOR = android.R.color.black;// 默认文字颜色

	public ClickableTextView(Context context) {
		super(context);
		initView(context, null);
	}

	public ClickableTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context, attrs);
	}

	public ClickableTextView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initView(context, attrs);
	}

	private void initView(Context context, AttributeSet attrs) {

		setClickable(true);
		setGravity(Gravity.CENTER);
		setIncludeFontPadding(false);
		if (null != attrs) {
			TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ClickableTextView);

			if (a.hasValue(R.styleable.ClickableTextView_cktv_color_n)) {
				mTextColor_n = a.getColor(R.styleable.ClickableTextView_cktv_color_n,DEFAULT_TEXT_COLOR);
			}

			if (a.hasValue(R.styleable.ClickableTextView_cktv_color_p)) {
				mTextColor_p = a.getColor(R.styleable.ClickableTextView_cktv_color_p,DEFAULT_TEXT_COLOR);
			}

			a.recycle();

			setEnabled(true);
			setTextCompat();

		}

	}
	
	

	/**
	 * 设置文字颜色
	 */
	private void setTextCompat() {

		if (mTextColor_n != -1 && mTextColor_p != -1) {
			int statePressed = android.R.attr.state_pressed;
			int stateFocesed = android.R.attr.state_focused;
			int[][] state = { { statePressed }, { -statePressed },
					{ stateFocesed }, { -stateFocesed } };

			int color_n = mTextColor_n;
			int color_p = mTextColor_p;
			int[] color = { color_p, color_n ,color_p,color_n};
			ColorStateList colorStateList = new ColorStateList(state, color);
			setTextColor(colorStateList);
		} else if (mTextColor_n != -1 && mTextColor_p == -1) {
			setTextColor(mTextColor_n);
		} else if (mTextColor_n == -1 && mTextColor_p != -1) {
			setTextColor(mTextColor_p);
		}

	}
	
	@Override
	public void setEnabled(boolean enabled) {
		// TODO Auto-generated method stub
		super.setEnabled(enabled);
		if(!enabled){
			setTextColor(getResources().getColor(R.color.enabled_color));
		}else{
			setTextCompat();
		}
	}

}